﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Enterprise.Management.Common
{
    public class UrlBuilder
    {
        private string url;
        private Dictionary<string, string> parameters;

        public UrlBuilder(string url)
        {
            Load(url);
            parameters = new Dictionary<string, string>();
        }

        public void Load(string url)
        {
            string[] urlparts = url.Split('?');
            this.url = urlparts[0];
            if (urlparts.Length > 1)
            {
                string[] paramArray = urlparts[1].Split('&');
                foreach (var item in paramArray)
                { 
                    var keyValue = item.Split('=');
                    AddParam(keyValue[0], keyValue[1]);
                }
            }
        }

        public void AddParam(string name, string value)
        {
            if (this.parameters.ContainsKey(name))
            {
                this.parameters[name] = value;
            }
            else
            { 
                this.parameters.Add(name, value);
            }
        }

        public string GetFullUrl()
        {
            string content = url;
            if (this.parameters.Count > 0)
            {
                content += "?";
            }
            foreach (string key in parameters.Keys)
            {
                if (!content.EndsWith("?")) content += "&";
                content += key + "=" + parameters[key];
            }

            return content;
        }

        public static string GenerateUrl(string action, string controller)
        {
            string virtualPath = HttpContext.Current.Request.ApplicationPath;
            if (!virtualPath.EndsWith("/"))
            {
                virtualPath += "/";
            }

            return string.Concat(virtualPath, controller, "/", action);
        }
    }
}